import { login, register, getUserInfo } from '@/api/user'
import { readToken, saveToken, saveUserInfo, deleteToken, readUserInfo } from '@/utils/auth'
import { encrypt } from '@/utils/encrypt'

// 获取默认状态
const getDefaultState = () => {
  return {
    token: readToken() || '',
    user_id: readUserInfo()?.user_id || '',
    name: readUserInfo()?.name || '',
    nikname: readUserInfo()?.nikname || '',
    avatar: readUserInfo()?.avatar || '',
    roles: readUserInfo()?.roles || []
  }
}

// 初始状态
const state = getDefaultState()

// 定义 mutations
const mutations = {
  // 重置状态
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  // 设置 token
  SET_TOKEN(state, token) {
    state.token = token
  },
  // 设置用户ID
  SET_ID: (state, id) => {
    state.user_id = id
  },
  // 设置用户名
  SET_NAME: (state, name) => {
    state.name = name
  },
  // 设置昵称
  SET_NICKNAME: (state, nikname) => {
    state.nikname = nikname
  },
  // 设置头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 设置角色
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

// 定义 actions
const actions = {
  // 注册
  async userRegister({ commit }, data) {
    const { username, password, email } = data
    // 加密密码
    const encryptedPassword = await encrypt(password)
    // 调用注册接口
    return new Promise((resolve, reject) => {
      register({ username: username.trim(), password: encryptedPassword, email: email.trim() })
        .then(async response => {
          const data = response
          // 本地存储
          saveToken(data.token)
          // 用户仓库存储
          commit('SET_TOKEN', data.token)
          // await dispatch('getUserInfo')
          resolve()
        })
        .catch(error => {
          console.log('error: ', error)
          reject(error)
        })
    })
  },
  // 登录
  async userLogin({ commit }, data) {
    const { username, password } = data
    // 加密密码
    const encryptedPassword = await encrypt(password)
    // 调用登录接口
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: encryptedPassword })
        .then(async response => {
          // 本地存储
          saveToken(response.data.token)
          // 用户仓库存储
          commit('SET_TOKEN', response.data.token)
          // await dispatch('getUserInfo')
          resolve()
        })
        .catch(error => {
          console.log('error: ', error)
          reject(error)
        })
    })
  },
  // 获取用户信息
  async userInfo({ commit }) {
    // 调用获取用户信息接口
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(response => {
          const data = response.data
          if (!data) {
            reject('验证失败，请重新登录!')
          }
          const { _id, roles, username, nikname, avatar } = data
          // 存储用户信息
          const userInfo = {
            user_id: _id,
            name: username,
            nikname: nikname,
            avatar: 'http://localhost:3000' + avatar,
            roles: roles
          }
          saveUserInfo(userInfo)
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles 必须是非空数组！')
          }
          commit('SET_ID', _id)
          commit('SET_ROLES', roles)
          commit('SET_NAME', username)
          commit('SET_NICKNAME', nikname)
          commit('SET_AVATAR', 'http://localhost:3000' + avatar)
          resolve(data)
        })
        .catch(error => {
          console.log('error: ', error)
          reject(error)
        })
    })
  },
  // 用户登出
  userLogout({ commit }, isRefurbish = true) {
    deleteToken()
    // 重置状态
    commit('RESET_STATE')
    // 刷新页面
    if (isRefurbish) {
      window.location.reload()
    }
  },
  // 移除 token
  resetToken({ commit }) {
    return new Promise(resolve => {
      deleteToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}
// 导出模块
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
